package com.czk.springcloud.controller;

import com.czk.springcloud.entity.CommonResult;
import com.czk.springcloud.entity.Payment;
import com.czk.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/12/16 16:57
 */
@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {

    @Value("${server.port}")
    private String serverPort;
    @Autowired
    private PaymentService paymentService;

    /**
     * 写
     *
     * @param payment
     * @return
     */
    @PostMapping("/insert")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("插入结果" + result);
        if (result > 0) {
            return new CommonResult(200, "插入成功" + serverPort, result);
        } else {
            return new CommonResult(500, "插入失败" + serverPort, result);
        }
    }

    /**
     * 读
     *
     * @param id
     * @return
     */
    @GetMapping("/select/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("查询结果" + payment);
        if (payment != null) {
            return new CommonResult(200, "查询成功" + serverPort, payment);
        } else {
            return new CommonResult(200, "查询失败" + serverPort, null);
        }
    }

    /**
     * 测试自定义负载均衡算法
     *
     * @return
     */
    @GetMapping("/lb")
    public String getPaymentLb() {
        return serverPort;
    }
    /**
     * 模拟feign调用超时
     * @return
     */
    @GetMapping("/feign/timeout")
    public String paymentFeignTimeout(){
        try {
            Thread.sleep(3*1000);
        }catch (InterruptedException ex){
            ex.printStackTrace();
        }
        return serverPort;
    }

}
